# 高德地图需求: json文件处理
# 1获取城市id:adcode
# 2根据adcode ,获取对应城市的天气
import requests
import re
import json
class Gaode(object):
    def __init__(self, url, filename):
        self.url = url
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                                      'Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.43'}
        self.filename = filename
    def city_code(self,serachname):
        response=requests.get(self.url,self.headers)
        res=response.json()
        city=res['data']
        cityData=city['cityData']
        hotCitys=cityData['hotCitys']
        provinces=cityData['provinces']
        #print(hotCitys)
        city_name=re.findall(".*?'name':(.*?),.*?",str(provinces))
        city_adcode=re.findall(".*?'adcode':(.*?),.*?",str(provinces))
        city_name1=re.findall("'(.*?)'",str(city_name))
        city_adcode1=re.findall("'(.*?)'",str(city_adcode))
        cityDict={}
        for i in range(len(city_name1)):
            cityDict[city_name1[i]]=city_adcode1[i]
        #print(cityDict['北京'])
        adcode=cityDict[serachname]
        return adcode
    def city_weather(self):
        url='https://amap.com/service/weather'
        searchname = input("输入城市名字：")
        adcode=self.city_code(searchname)
        params={
            'adcode':adcode
        }
        response = requests.get(url,params=params,headers=self.headers)
        res=response.json()
        city = res['data']
        data = city['data']
        report_time=re.findall(".*?'report_time': (.*?), 'live':.*?",str(data),re.S)
        report_time1=re.findall("'(.*?)'",str(report_time))
        weather=re.findall(".*?'live': {'weather_name': (.*?),.*?",str(data))
        weather1=re.findall("'(.*?)'",str(weather))
        temperature=re.findall(".*?'temperature': (.*?)}, 'forecast_date':.*?",str(data))
        temperature1=re.findall("'(.*?)'",str(temperature))
        print(searchname+'天气：'+weather1[0]+'\t'+'温度'+temperature1[0]+'\t'+'时间'+report_time1[0])
        # print(rs_weather.items())



def main():
    url='https://amap.com/service/cityList'
    gaode=Gaode(url,'cityList')
    gaode.city_weather()

if __name__=='__main__':
    main()
